#!/usr/bin/python
# -*- coding: UTF-8 -*-
# author:heqiang

from flask import Flask, request, make_response, render_template, redirect
import messageManage
import re, json, time
import requests
import taobao.aetaoke as aetaoke
import model
import xml.etree.cElementTree as ET
from global_token import *
import traceback


def get_token():
    payload_access_token = {
        'grant_type': 'client_credential',
        'appid': 'wxd9cfdc38b3bf4c23',
        'secret': 'fcae013247960e926065a8d6a3e98f88'
    }
    token_url = 'https://api.weixin.qq.com/cgi-bin/token'
    r = requests.get(token_url, params=payload_access_token)
    dict_result = (r.json())
    return dict_result['access_token']


def get_media_ID(path):
    img_url = 'https://api.weixin.qq.com/cgi-bin/material/add_material'
    access_token = get_token()
    payload_img = {
        'access_token': access_token,
        'type': 'image'
    }
    data = {'media': open(path, 'rb')}
    r = requests.post(url=img_url, params=payload_img, files=data)
    dict = r.json()
    return access_token


def downImg(yourtoken):
    url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=%s" % (yourtoken)

    datas = {
        "type": "image",
        "offset": 0,
        "count": 20
    }
    data = json.dumps(datas)
    a = requests.post(url=url, data=data)
    print(a.text)


def recv_reply_msg(rec):
    """
    处理收到的微信消息
    :param rec:
    :return:
    """

    xml = ET.fromstring(rec)
    # 检查是否重复消息
    try:
        msgID = xml.find('MsgId').text
    except:
        aetaoke.log.error("获取msgID失败，原因:\n%s\n%s" % (traceback.format_exc(limit=4), rec))
        return ""
    if msgID in global_msg_ids:
        print("重复消息，屏蔽")
        return ""
    else:
        global_add_msg(msgID)

    toUser = xml.find('ToUserName').text
    fromUser = xml.find('FromUserName').text  # 微信号
    msgType = xml.find("MsgType").text
    if msgType == 'text':
        content = xml.find('Content').text

        # 绑定淘宝订单
        if re.search(r"^\d{18,25}", content):
            try:
                trade_id = re.search(r"^\d{18,25}", content).group()
                replay_msg = aetaoke.bond_order(wx_id=fromUser, trade_id=trade_id)
            except Exception as e:
                aetaoke.log.warning("%s———订单绑定失败，请检查订单正确性哦" % content)
                aetaoke.log.error(aetaoke.traceback.format_exc(limit=3))
                replay_msg = "\ue045———订单绑定失败，请检查订单正确性哦"


        # 判断是否为淘口令
        elif re.search(r"\w{10}", content):
            replay_msg = aetaoke.tkl_api(content, username=fromUser, wx_id=fromUser)

        # 查询用户返利总额
        elif re.search(r"^查询", content):
            try:
                total_fee, nodone_fee = aetaoke.query_total_fee(wx_id=fromUser)
                replay_msg = messageManage.TOTAL_FEE_MSG % (total_fee, nodone_fee)
            except Exception as e:
                model.add_user(username=fromUser, wx_id=fromUser)
                total_fee, nodone_fee = aetaoke.query_total_fee(wx_id=fromUser)
                replay_msg = messageManage.TOTAL_FEE_MSG % (total_fee, nodone_fee)
        # 执行提现
        elif re.search(r"^提现", content):
            replay_msg = aetaoke.transfer_fee(wx_id=fromUser)
        elif re.search(r"^订单", content):
            # 查询所有订单
            orders = model.get_user_orders(wx_id=fromUser)
            replay_msg = "\ue148您所有的未关闭订单如下：\n%s" % (orders)
        # 执行付款
        elif re.search(r"^打赏$", content):
            try:
                fee = re.search(r"\d+", content).group()
            except:
                fee = 1
            if int(fee) >= 100:
                fee = "100"
            replay_msg = "感谢您的打赏，已生成支付订单：\n%s/pay?wx=%s&fee=%s" % (messageManage.URL, fromUser, fee)

        # 使用指导
        elif re.search(r"^帮助", content):
            replay_msg = messageManage.HELPINFO
            # 图片
        else:
            result = aetaoke.search_product(wx_id=fromUser, txt=content)
            if result:
                replay_msg = messageManage.SEARCH_INFO
            else:
                replay_msg = messageManage.HELPINFO

        reply = '''<xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%s</CreateTime>
                <MsgType><![CDATA[%s]]></MsgType>
                <Content><![CDATA[%s]]></Content>
                </xml>'''
        response = make_response(reply % (fromUser, toUser, str(int(time.time())), "text", replay_msg))
        response.headers['content-type'] = 'application/xml'
        return response

    # 关注事件，取消关注事件处理
    elif msgType == 'event':
        content = xml.find('Event').text
        if content == "subscribe":
            model.add_user(username=fromUser, wx_id=fromUser)
            replay_msg = messageManage.HELPINFO

            reply = '''<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <Content><![CDATA[%s]]></Content>
                            </xml>'''
            response = make_response(reply % (fromUser, toUser, str(int(time.time())), "text", replay_msg))
            response.headers['content-type'] = 'application/xml'
            return response

        elif content == "unsubscribe":
            model.del_user(fromUser)
            response = make_response("ok")
            response.headers['content-type'] = 'application/xml'
            return response
        else:
            return False
    else:
        # 包含图片，语音，视频等消息类型
        replay_msg = messageManage.HELPINFO

        reply = '''<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[%s]]></MsgType>
                        <Content><![CDATA[%s]]></Content>
                        </xml>'''
        response = make_response(reply % (fromUser, toUser, str(int(time.time())), "text", replay_msg))
        response.headers['content-type'] = 'application/xml'
        return response


# def get_openid(self):
#     """
#     获取所有粉丝的openid
#     """
#     next_openid = ''
#     url_openid = 'https://api.weixin.qq.com/cgi-bin/user/get?access_token=%s&next_openid=%s' % (
#         self.access_token, next_openid)
#     ans = requests.get(url_openid)
#     print(ans.content)
#     open_ids = json.loads(ans.content)['data']['openid']
#     return open_ids


"""
主动发送消息
"""

# def sendmsg(msg, wx_id):
#     """
#     给所有粉丝发送文本消息
#     """
#     access_token = get_token()
#     url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={}".format(access_token)
#     body = {
#         "touser": wx_id,
#         "msgtype": "text",
#         "text":
#             {
#                 "content": msg
#             }
#     }
#     data = bytes(json.dumps(body, ensure_ascii=False).encode('utf-8'))
#     # print(data)
#     response = requests.post(url, data=data)
#     # 这里可根据回执code进行判定是否发送成功(也可以根据code根据错误信息)
#     result = response.json()
#     # print(result)


if __name__ == "__main__":
    pass
    # sendmsg(msg="调试", wx_id="oxVH76sARK3kcWQMvS8Zpr0kE6gY")
    # total_fee, nodone_fee = aetaoke.query_total_fee(wx_id="oxVH76qz2we4yyk-RaGrgpv8eIZE")
    # print(total_fee, nodone_fee)
    #     a = "<xml><ToUserName><![CDATA[gh_9916f0d0036e]]></ToUserName>\
    # <FromUserName><![CDATA[oYzyEv5y_PWiC3_8BuaH90Lw-BMk]]></FromUserName>\
    # <CreateTime>1596771619</CreateTime>\
    # <MsgType><![CDATA[text]]></MsgType>\
    # <Content><![CDATA[查询]]></Content>\
    # <MsgId>22860274477589510</MsgId>\
    # </xml>"
    #     parse_msg(a.encode("utf-8"))

